package com.tensquare.spit.service;

/**
 * @author fangyu
 * @version v1.0.0
 * @date 2020/10/13 7:10 下午
 */

import com.tensquare.common.util.IdWorker;
import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SpitService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询全部记录
     * @return List<Spit>
     */
    public List<Spit> findAll() {
        return spitDao.findAll();
    }

    /**
     * 根据主键查询实体
     * @param id 主键
     * @return
     */
    public Spit findById(String id) {
        return spitDao.findById(id).get();
    }

    /**
     * 发布吐槽(或吐槽评论)
     * @param spit 实体类
     */
    public void add(Spit spit) {
        // 设置主键值(雪花算法)
        spit.set_id(idWorker.nextId()+"");
        // 发布日期
        spit.setPublishtime(new Date());
        // 浏览量
        spit.setVisits(0);
        // 分享数
        spit.setShare(0);
        // 点赞数
        spit.setThumbup(0);
        // 回复数
        spit.setComment(0);
        // 状态
        spit.setState("1");
        // 如果存在上级ID, 评论
        if (spit.getParentid()!=null && !"".equals(spit.getParentid())){
           Query query = new Query();
           query.addCriteria(Criteria.where("id").is(spit.getParentid()));
           Update update = new Update();
           update.inc("comment", 1);
           mongoTemplate.updateFirst(query, update, "spit");
        }
        spitDao.save(spit);
    }

    /**
     * 修改
     * @param spit 实体类
     */
    public void update(Spit spit) {
        spitDao.save(spit);
    }

    /**
     * 删除
     * @param id 主键
     */
    public void deleteById(String id) {
        spitDao.deleteById(id);
    }

    /**
     * 根据上级ID查询吐槽列表
     * @param parentId 上级ID
     * @param page 页码
     * @param size 页大小
     * @return Page
     */
    public Page<Spit> findByParentId(String parentId, int page, int size) {
        PageRequest pageRequest = PageRequest.of(page, size);
        return spitDao.findByParentid(parentId, pageRequest);
    }

    /**
     * 点赞
     * @param id 主键
     */
    public void updateThumbup(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query,update,"spit");
    }
}
